﻿using EFFC.Frame.Net.Module.Extend.EWRA.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using EFFC.Extends.LinqDLR2SQL;
using EFFC.Frame.Net.Base.Common;
using EFFC.Frame.Net.Unit.DB;
using EFFC.Frame.Net.Module.Extend.EWRA.Attributes.Validation;
using ICPFrameLib.Business;
using ICPFrameLib.Attributes;

namespace XHRPMIS.Business.v1._0
{
    public class RoleAuth:MyRestLogic
    {
        [ActionAuth("RoleAuth")]
        [EWRARouteDesc("根据角色编号获取该角色下的账号和功能权限设定")]
        [EWRAAddInput("id", "string", "角色编号", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息"",
data:{
        login:[数据集],
        function:[数据集]
    }
}")]
        public override object get(string id)
        {
            SetCacheEnable(false);
            var up = DB.NewMetaUnitParameter();
            var roleloginlist = (from t in DB.LamdaTable(up, "EXTEND_ROLE_LOGIN", "a")
                    join t2 in DB.LamdaTable(up, "EXTEND_LOGIN", "b").LeftJoin() on t.loginuid equals t2.uid
                    where t.roleno == id
                    select new
                    {
                        t.loginuid,
                        t2.loginid,
                        t2.userno,
                        t2.usertype,
                        t.roleno
                    }).GetQueryList(up);
            var rolefunctionlist = (from t in DB.LamdaTable(up, "EXTEND_ROLE_FUNCTION", "a")
                                    join t2 in DB.LamdaTable(up, "EXTEND_FUNCTION", "b") on t.functionno equals t2.functionno
                                    where t.roleno == id
                                    select new
                                    {
                                        t.functionno,
                                        t2.functionname,
                                        t.roleno
                                    }).GetQueryList(up);
            return new
            {
                code = "success",
                msg = "",
                data = new
                {
                    login = roleloginlist,
                    function = rolefunctionlist
                }
            };
        }
        [ActionAuth("RoleAuth")]
        [EWRARoute("post", "/roleauth/login2role")]
        [EWRARouteDesc("将指定的登录账号给一个角色")]
        [EWRAEmptyValid("loginuid,roleno")]
        [EWRAAddInput("loginuid", "string", "登录账号的UID，多个uid用逗号分隔", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAAddInput("roleno", "string", "角色编号,只能单个角色编号", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息""
}")]
        object DoAuthLoginRole()
        {
            string strroleno = ComFunc.nvl(PostDataD.roleno);
            string strloginuid = ComFunc.nvl(PostDataD.loginuid);

            var loginuids = strloginuid.Split(',').Where(p => p.Trim() != "");

            BeginTrans();
            var up = DB.NewMetaUnitParameter();
            if (!(from t in DB.LamdaTable(up, "EXTEND_ROLE", "a")
                  where t.roleno == strroleno
                  select t).IsExists(up))
            {
                return new
                {
                    code = "failed",
                    msg = "角色编号无效"
                };
            }
            foreach(var login in loginuids)
            {
                if (!(from t in DB.LamdaTable(up, "EXTEND_LOGIN", "a")
                      where t.uid == login
                      select t).IsExists(up))
                {
                    return new
                    {
                        code = "failed",
                        msg = "登录账号无效"
                    };
                }
            }
            

            (from t in DB.LamdaTable(up, "EXTEND_ROLE_LOGIN", "a")
             where t.roleno == strroleno
             select t).Delete(up);

            foreach (var login in loginuids)
            {
                DB.QuickInsert(up, "EXTEND_ROLE_LOGIN", new
                {
                    loginuid = login,
                    roleno = strroleno,
                    add_id = TokenPayLoad.ID,
                    add_ip = ClientInfo.IP,
                    add_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    last_id = TokenPayLoad.ID,
                    last_ip = ClientInfo.IP,
                    last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                });
            }

            CommitTrans();
            return new
            {
                code = "success",
                msg = "授权成功"
            };
        }
        [ActionAuth("RoleAuth")]
        [EWRARoute("post","/roleauth/role2login")]
        [EWRARouteDesc("将指定的角色授权给一个登录账号")]
        [EWRAEmptyValid("loginuid,roleno")]
        [EWRAAddInput("loginuid", "string", "登录账号的UID，只能单个登录账号", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAAddInput("roleno", "string", "角色编号，多个角色编号用逗号分隔", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息""
}")]
        object DoAuthRoleLogin()
        {
            string strroleno = ComFunc.nvl(PostDataD.roleno);
            string strloginuid = ComFunc.nvl(PostDataD.loginuid);

            var rolenos = strroleno.Split(',').Where(p => p.Trim() != "");

            BeginTrans();
            var up = DB.NewMetaUnitParameter();
            if (!(from t in DB.LamdaTable(up, "EXTEND_LOGIN", "a")
                  where t.uid == strloginuid
                  select t).IsExists(up))
            {
                return new
                {
                    code = "failed",
                    msg = "登录账号无效"
                };
            }
           
            foreach (var role in rolenos)
            {
                if (!(from t in DB.LamdaTable(up, "EXTEND_ROLE", "a")
                      where t.roleno == role
                      select t).IsExists(up))
                {
                    return new
                    {
                        code = "failed",
                        msg = "角色编号无效"
                    };
                }
            }

            (from t in DB.LamdaTable(up, "EXTEND_ROLE_LOGIN", "a")
             where t.loginuid == strloginuid
             select t).Delete(up);

            foreach (var role in rolenos)
            {
                DB.QuickInsert(up, "EXTEND_ROLE_LOGIN", new
                {
                    loginuid = strloginuid,
                    roleno = role,
                    add_id = TokenPayLoad.ID,
                    add_ip = ClientInfo.IP,
                    add_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    last_id = TokenPayLoad.ID,
                    last_ip = ClientInfo.IP,
                    last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                });
            }

            CommitTrans();
            return new
            {
                code = "success",
                msg = "授权成功"
            };
        }
        [ActionAuth("RoleAuth")]
        [EWRARoute("post", "/roleauth/rolefunction")]
        [EWRARouteDesc("给指定的角色进行功能授权")]
        [EWRAEmptyValid("functionnos,roleno")]
        [EWRAAddInput("roleno", "string", "角色编号", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAAddInput("functionnos", "string", "功能编号，多个功能编号用逗号分隔", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAOutputDesc("返回结果", @"{
code:""success-成功，failed-失败"",
msg:""提示信息""
}")]
        object DoAuthRoleFunction()
        {
            var roleno = ComFunc.nvl(PostDataD.roleno);
            string functionnos = ComFunc.nvl(PostDataD.functionnos);

            BeginTrans();
            var up = DB.NewMetaUnitParameter();
            
            if (!(from t in DB.LamdaTable(up, "EXTEND_ROLE", "a")
                  where t.roleno == roleno
                  select t).IsExists(up))
            {
                return new
                {
                    code = "failed",
                    msg = "角色编号无效"
                };
            }
            var s = from t in DB.LamdaTable(up, "EXTEND_ROLE_FUNCTION", "a")
                    where t.roleno == roleno
                    select t;

            s.Delete(up);
            var arr = functionnos.Split(',');
            foreach(var f_no in arr)
            {
                DB.QuickInsert(up, "EXTEND_ROLE_FUNCTION", new
                {
                    functionno = f_no,
                    roleno = roleno,
                    add_id = TokenPayLoad.ID,
                    add_ip = ClientInfo.IP,
                    add_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    last_id = TokenPayLoad.ID,
                    last_ip = ClientInfo.IP,
                    last_time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
                });
            }

            CommitTrans();
            return new
            {
                code = "success",
                msg = "授权成功"
            };
        }
        [ActionAuth("RoleAuth")]
        [EWRARoute("delete", "/roleauth/rolefunction")]
        [EWRARouteDesc("将指定的角色功能授权进行删除")]
        [EWRAEmptyValid("functionnos,roleno")]
        [EWRAAddInput("roleno", "string", "角色编号", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.Path, false)]
        [EWRAAddInput("functionnos", "string", "功能编号，多个功能编号用逗号分隔", "无默认值", EFFC.Frame.Net.Base.Constants.RestInputPosition.PostData, false)]
        [EWRAOutputDesc("返回结果", @"根据HTTP status判定，204:成功，404:失败，可能原因，未找到数据")]
        bool DeleteAuthRoleFunction()
        {
            var roleno = ComFunc.nvl(PostDataD.roleno);
            string functionnos = ComFunc.nvl(PostDataD.functionnos);

            BeginTrans();
            var up = DB.NewMetaUnitParameter();

            if (!(from t in DB.LamdaTable(up, "EXTEND_ROLE", "a")
                  where t.roleno == roleno
                  select t).IsExists(up))
            {
                return false;
            }
            var s = from t in DB.LamdaTable(up, "EXTEND_ROLE_FUNCTION", "a")
                    where t.roleno == roleno && t.functionno.within(functionnos)
                    select t;

            s.Delete(up);
            
            CommitTrans();
            return true;
        }
    }
}
